09. Using Gulp w/ Autoprefixer

Using Gulp 2

Recap: gulp-autoprefixer Setup

Why Use Autoprefixer?

Since different browsers tend to use different vendor prefixes, making sure your CSS is compatible across different browsers can get messy quickly. Autoprefixer streamlines writing CSS by automatically adding vendor prefixes! For example, this allows you to simply write:

.navigation {
  display: flex
}

Autoprefixer will then take the above code and produce this in the compiled CSS:

.navigation {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex
}

Installing Autoprefixer

The installation and setup process is quite similar to how we got Sass with Gulp up and running. We begin by installing gulp-autoprefixer into our devDependencies with the following command:

npm install --save-dev gulp-autoprefixer

Then, we require it in our gulpfile.js file with the expression:

const autoprefixer = require('gulp-autoprefixer');

Finally, we modify the existing "styles" task in our gulpfile.js file. The finished result should look like this:

gulp.task("styles", function() {
  gulp
    .src("sass/**/*.scss")
    .pipe(sass())
    .on("error", sass.logError)
    .pipe(
      autoprefixer({
        browsers: ["last 2 versions"]
      })
    )
    .pipe(gulp.dest("./css"));
});

In the above code, after running Sass (and logging errors should there be any), we run Autoprefixer. We then prefix the last the two versions of all browsers before finally giving Gulp the write path for the CSS file.

Feel free to check out more about gulp-autoprefixer here.